import React, { Component, Fragment } from 'react';
import { Form, Input, Select, DatePicker, Button, Modal } from 'antd';
import { connect } from 'dva';
import Media from 'react-media';
import SelectForm from '@/components/SelectForm';
import ManageList from '@/components/ManageList';
import TableButtons from '@/components/TableButtons';
import RightDraw from '@/components/RightDraw';
import StandardTable from '@/components/StandardTable';
import InsuranceDetail from './InsuranceDetail';
import styles from './InsuranceList.less';
import AntdFormItem from '@/components/AntdFormItem';
import AdSelect from '@/components/AdSelect';
import { billStateList, billStateOnlyReadList } from '@/utils/constans';
import { vitifyCheck, formateDateToMin } from '@/utils/common';
import moment from 'moment';
import AdSearch from '@/components/AdSearch';
import AntdDatePicker from '@/components/AntdDatePicker';
import router from 'umi/router';
import SearchSelect from '@/components/SearchSelect';
import { columns1, columnsBillNo } from '@/pages/Common/common';
import AdButton from '@/components/AdButton';
import { codes } from './utils';

const { RangePicker } = DatePicker;
const dateFormat = 'YYYY-MM-DD';
const FormItem = Form.Item;
const { Option } = Select;
const confirm = Modal.confirm;

@ManageList
@connect(({ insurance, component, loading, common }) => ({
  insurance,
  loading: loading.models.insurance,
  ownCompany: common.ownCompany,
  searchValue: component.searchValue,
  dictObject: common.dictObject,
}))
@Form.create()
export default class InsuranceList extends Component {
  state = {
    visible: false,
    id: '',
    formValues: {},
    cars: [],
    billNos: [],
    expandForm: false,
    selectedRows: [],
    isBillStatus: '',
  };
  className = 'InsuranceList';
  columns = [
    {
      title: '单据号',
      dataIndex: 'insuranceNo',
      fixed: this.props.isMobile ? false : true,
      render: (text, record) => (
        <AdButton
          mode="a"
          onClick={e => this.showDetail(e, record.id, record)}
          text={text}
          code={codes.showDetail}
        />
      ),
    },
    {
      title: '状态',
      dataIndex: 'billStatus',
      render: (text, record) => (
        <AdSelect
          onlyRead={true}
          value={text ? text : record.status}
          data={billStateOnlyReadList}
        />
      ),
      width: 100,
    },
    {
      title: '保险对象',
      dataIndex: 'insuranceObject',
      render: text => (
        <AdSelect onlyRead={true} value={text} data={this.props.dictObject['insurance-object']} />
      ),
    },
    {
      title: '代理购买保险人',
      dataIndex: 'agentPurchaser',
    },
    {
      title: '主车牌',
      dataIndex: 'cartPlateNo',
    },
    {
      title: '所属公司',
      dataIndex: 'ownCompanyName',
      width: 250,
      render: text => <span title={text}>{text}</span>,
    },
    {
      title: '保险类型',
      dataIndex: 'insuranceTypeCode',
      render: text => (
        <AdSelect onlyRead={true} value={text} data={this.props.dictObject['insurance-type']} />
      ),
    },
    {
      title: '保险公司',
      dataIndex: 'company',
    },
    {
      title: '保单号',
      dataIndex: 'insuranceCode',
      render: text => <span title={text}>{text}</span>,
      width: 200,
    },
    {
      title: '有效期',
      dataIndex: 'expiryTime',
      render: (text, record) => <span>{`${record.expiryStartTime}~${record.expiryEndTime}`}</span>,
      width: 200,
    },
    {
      title: '保费金额',
      dataIndex: 'insuranceMoney',
    },
    {
      title: '币种',
      dataIndex: 'currencyType',
      render: text => (
        <AdSelect onlyRead={true} value={text} data={this.props.dictObject['currency-type']} />
      ),
      width: 100,
    },
    {
      title: '账单号',
      dataIndex: 'billNo',
    },
    {
      title: '创建人',
      dataIndex: 'createBy',
      render: text => (
        <AdSearch
          label="loginName"
          name="sysName"
          value={this.props.searchValue[text]}
          onlyRead={true}
        />
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      render: text => <span>{text ? moment(text).format(formateDateToMin) : ''}</span>,
    },
    {
      title: '更新人',
      dataIndex: 'updateBy',
      render: text => (
        <AdSearch
          label="loginName"
          name="sysName"
          value={this.props.searchValue[text]}
          onlyRead={true}
        />
      ),
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      render: text => <span>{text ? moment(text).format(formateDateToMin) : ''}</span>,
    },
  ];

  componentDidMount() {
    this.dispatchFun('insurance/insuranceList', {});
    // this.dispatchFun('insurance/carList', { pageSize: 1000 });

    // 查询字典： 保险类型
    this.props.dispatch({
      type: 'common/querytDictByCode',
      payload: { code: 'insurance-type' },
    });
    // 币种
    this.props.dispatch({
      type: 'common/querytDictByCode',
      payload: { code: 'currency-type' },
    });
    // 保险对象
    this.props.dispatch({
      type: 'common/querytDictByCode',
      payload: { code: 'insurance-object' },
    });
  }

  // 分页操作
  handleStandardTableChange = param => {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    const params = {
      ...formValues,
      ...param,
    };
    this.dispatchFun('insurance/insuranceList', params);
  };

  // 重置条件查询表单
  handleFormReset = () => {
    this.setState({ formValues: {}, cars: [], billNos: [] });
    this.dispatchFun('insurance/insuranceList', {});
  };

  // 执行条件查询表单
  handleSearch = values => {
    // if (!values) {
    //   return;
    // }
    const { expiryTime, ...value } = values;
    if (expiryTime) {
      value.expiryStartTime = moment(expiryTime[0]).format(dateFormat);
      value.expiryEndTime = moment(expiryTime[1]).format(dateFormat);
    }
    const { cars, billNos } = this.state;
    if (cars.length > 0) {
      const vehicleId = cars.map(v => {
        return v.id;
      });
      value.vehicleId = vehicleId.join(',');
    } else {
      value.vehicleId = '';
    }
    if (billNos.length > 0) {
      const billId = billNos.map(v => {
        return v.id;
      });
      value.billId = billId.join(',');
    } else {
      value.billId = '';
    }
    this.setState({
      formValues: value,
    });
    this.dispatchFun('insurance/insuranceList', value);
  };

  toggleForm = expandForm => {
    this.setState({
      expandForm,
    });
  };

  // 跳转 新增页面
  handleAdd = () => {
    const { dispatch } = this.props;
    router.push('/carDaily/insuranceList/addInsurance');
  };

  // 跳转 编辑页面
  handleEdit = () => {
    const { id } = this.state;
    this.closeDetail();
    router.push(`/carDaily/insuranceList/editInsurance/${id}`);
  };

  // 关闭右抽屉
  closeDetail = () => {
    this.setState({
      visible: false,
    });
  };
  // 打开右抽屉
  showDetail = (e, id, record) => {
    e.stopPropagation();
    const status = record.billStatus ? record.billStatus : record.status;
    const isBillStatus = status === 'CONFIRM' || status === 'WAIT';
    this.setState({
      visible: true,
      isBillStatus,
      id,
    });
    this.dispatchFun('insurance/insuranceDetail', { id });
  };

  // dispatch 方法
  dispatchFun(type, params) {
    const { dispatch, searchValue } = this.props;
    dispatch({
      type: type,
      payload: params,
      callback: data => {
        if (type === 'insurance/insuranceList' && data) {
          let valueList = [];
          data.map(v => {
            const labels = ['updateBy', 'createBy'];
            labels.map(item => {
              if (v[item] && !valueList.includes(v[item])) {
                valueList.push(v[item]);
                !searchValue[v[item]] &&
                  dispatch({
                    type: 'component/querySearchValue',
                    payload: {
                      params: { loginName: v[item] },
                      url: 'tms/tms-insurance/selectInsuranceUser_s',
                    },
                  });
              }
            });
          });
        }
      },
    });
  }

  /**
   * 生成账单
   */
  generatedBills = () => {
    const { dispatch } = this.props;
    const { selectedRows, formValues } = this.state;
    const checkBill = this.checkBill();
    if (!checkBill) return;
    dispatch({
      type: 'insurance/generatedBills',
      payload: { ids: selectedRows.map(v => v.id) },
      callback: data => {
        if (!data) return;
        this.setState({
          selectedRows: [],
        });
        this.dispatchFun('insurance/insuranceList', formValues);
        //跳转到账单的编辑页面
        router.push(`/carAccount/billList/editBill/${data}`);
      },
    });
  };

  /**
   * 生成账单校验 状态已提交，同一公司，同一加油方式
   */

  checkBill = () => {
    const { selectedRows } = this.state;
    const ownCompanyName = vitifyCheck({
      selectedRows,
      key: 'ownCompanyName',
      warn: '所选记录必须所属公司相同！',
    });
    if (!ownCompanyName) return false;
    return true;
  };

  getValue = (values, type) => {
    this.setState({
      [type]: values,
    });
  };
  handleSelectRows = selectedRows => {
    this.setState({
      selectedRows,
    });
  };
  //删除
  removeRecord = () => {
    const { dispatch } = this.props;
    const { id, visible, formValues } = this.state;
    confirm({
      title: '确定要删除这条数据吗？',
      content: ' ',
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk: () => {
        dispatch({
          type: 'insurance/deleteInsurance',
          payload: { id: id },
          callback: () => {
            this.setState({ visible: false, selectedRows: [] });
            this.dispatchFun('insurance/insuranceList', formValues);
          },
        });
      },
    });
  };

  selectAll = () => {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    dispatch({
      type: 'insurance/selectAll',
      payload: formValues,
      callback: data => {
        this.setState({
          selectedRows: [],
        });
        if (!data) return;

        this.dispatchFun('insurance/insuranceList', formValues);
        //跳转到账单的编辑页面
        router.push(`/carAccount/billList/editBill/${data}`);
      },
    });
  };

  render() {
    const {
      form,
      loading,
      insurance: { insuranceList, detail },
      isMobile,
      ownCompany,
      dictObject,
    } = this.props;
    const { id, visible, expandForm, formValues, selectedRows, isBillStatus } = this.state;
    const { getFieldDecorator } = form;
    const commonParams = {
      getFieldDecorator,
    };
    // firstForm 参数
    const firstFormItem = (
      <FormItem label="单据号">
        {getFieldDecorator('insuranceNo')(<Input placeholder="请输入" />)}
      </FormItem>
    );
    const secondFormItem = (
      <AntdFormItem label="状态" code="billStatus" {...commonParams}>
        <AdSelect isExist={true} data={billStateList} mode="multiple" />
      </AntdFormItem>
    );
    // secondForm 参数
    const otherFormItem = [
      [
        <FormItem label="保单号">
          {getFieldDecorator('insuranceCode')(<Input placeholder="请输入" />)}
        </FormItem>,
      ],
      [
        <FormItem label="车牌号">
          {getFieldDecorator('vehicleId')(
            <SearchSelect
              dataUrl="tms/tms-insurance/selectInsuranceVehicle"
              url="tms/tms-insurance/selectInsuranceVehicleView_s" // selectedData只只有id时需要传url
              selectedData={this.state.cars} // 选中值
              multiple={false} // 是否多选
              showValue="cartPlateOneNo"
              searchName="cartPlate"
              columns={columns1} // 表格展示列
              onChange={values => this.getValue(values, 'cars')} // 获取选中值
              scrollX={480}
              id="InsuranceList_1"
              allowClear={true}
            />
          )}
        </FormItem>,
        <FormItem label="所属公司">
          {getFieldDecorator('ownCompanyId')(
            <Select
              allowClear={true}
              showSearch
              filterOption={(input, option) =>
                option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
              }
              placeholder="请选择"
              style={{ width: '100%' }}
            >
              <Option value="">请选择</Option>
              {ownCompany.map((v, i) => {
                return (
                  <Option key={i} value={v.customerCode}>
                    {v.customerName}
                  </Option>
                );
              })}
            </Select>
          )}
        </FormItem>,
        <FormItem label="保险类型">
          {getFieldDecorator('insuranceTypeCode')(
            <Select placeholder="请选择" allowClear={true}>
              <Option value="">请选择</Option>
              {dictObject['insurance-type'] &&
                dictObject['insurance-type'].map(item => (
                  <Option key={item.code}>{item.value}</Option>
                ))}
            </Select>
          )}
        </FormItem>,
      ],
      [
        <FormItem label="到期时间">
          {getFieldDecorator('expiryTime')(<AntdDatePicker mode="range" />)}
        </FormItem>,
        <FormItem label="账单号">
          {getFieldDecorator('billId')(
            <SearchSelect
              dataUrl="tms/tms-insurance/selectTmsBillList_s"
              selectedData={this.state.billNos} // 选中值
              multiple={false} // 是否多选
              showValue="billNo"
              searchName="billNo"
              columns={columnsBillNo} // 表格展示列
              onChange={values => this.getValue(values, 'billNos')} // 获取选中值
              scrollX={200}
              id="InsuranceList_2"
              allowClear={true}
              payload={{ type: 'INSURANCE' }}
            />
          )}
        </FormItem>,
        'operatorButtons',
      ],
    ];

    const selectFormParams = {
      firstFormItem,
      secondFormItem,
      otherFormItem,
      form,
      code: codes.select,
      className: this.className,
      handleFormReset: this.handleFormReset,
      handleSearch: this.handleSearch,
      toggleForm: this.toggleForm,
    };

    const tableButtonsParams = {
      show: false,
      code: codes.add,
      handleAdd: this.handleAdd,
      selectedLength: selectedRows.length,
      pagination: insuranceList.pagination,
      selectAll: this.selectAll,
      code: codes.bill,
      buttons: (
        <AdButton
          disabled={!selectedRows.length > 0}
          onClick={() => this.generatedBills()}
          text={`生成账单${selectedRows.length > 0 ? '(' + selectedRows.length + ')' : ''}`}
          code={codes.bill}
        />
      ),
    };

    const rightDrawParams = {
      isMobile,
      visible,
      title: '保险详情',
      code: codes.showDetail,
      closeDetail: this.closeDetail,
      buttons: (
        <span>
          <AdButton
            onClick={() => this.removeRecord(1)}
            text="删除"
            type="danger"
            style={{ marginRight: 10 }}
            ghost
            code={codes.remove}
            disabled={!isBillStatus}
          />
          <AdButton
            onClick={this.handleEdit}
            disabled={!isBillStatus}
            text="编辑"
            type="primary"
            code={codes.showDetail}
          />
        </span>
      ),
    };
    const billStatus = formValues.billStatus;
    const disabledRowSelected =
      billStatus && billStatus.length === 1 && billStatus.includes('CONFIRM') ? false : true;
    return (
      <Fragment>
        <SelectForm {...selectFormParams} />
        <TableButtons {...tableButtonsParams} />
        <StandardTable
          selectedRows={selectedRows}
          getCheckboxProps={record => {
            const status = record.billStatus ? record.billStatus : record.status;
            const checked = status === 'CONFIRM' || status === 'WAIT';
            return !checked;
          }}
          loading={loading}
          data={insuranceList}
          onSelectRow={this.handleSelectRows}
          columns={this.columns}
          onPaginationChange={this.handleStandardTableChange}
          expandForm={expandForm}
          disabledSelectedRows={{ code: ['billStatus', 'status'], value: ['CONFIRM', 'WAIT'] }}
          className={this.className}
          code={codes.page}
        />
        <RightDraw {...rightDrawParams}>
          <InsuranceDetail isMobile={isMobile} id={id} />
        </RightDraw>
      </Fragment>
    );
  }
}
